<?php
namespace app\admin\controller;
use \think\Controller;
use \think\Db;
use \think\Loader;
use \think\Validate;
class Admin extends Controller
{
    public function index()
    {
        $userData = Db::table('admin t1')
        ->join('auth_admin_role t2','t1.aid = t2.aid')
        ->join('auth_role t3','t2.roid = t3.roid')
        ->field('t1.*,t3.rname')
        ->paginate(1);
        return $this->fetch('',['userData'=>$userData]);
    }

    public function status()
    {
        $aid = input('aid');
        $status = Db::table('admin')->where(['aid'=>$aid])->value('status');
        if ($status) {
            $res = Db::table('admin')->where(['aid'=>$aid])->update(['status'=>'0']);
        }else{
            $res = Db::table('admin')->where(['aid'=>$aid])->update(['status'=>'1']);
        }
        if($res){
            return['error'=>0,'info'=>'success'];
        }else{
            return['error'=>1,'info'=>'系统异常'];
        }
    }

    public function add(){
        $role = DB::table('auth_role')->select();
        // var_dump($cate);
        return $this->fetch('add',['role'=>$role]);

    }

    public function addsubmit(){
        $data = input('post.');
        $data['repassword']=$data['repass'];      
        $data['password']=$data['pass'];
        $data['ctime'] = time();
        $validate = Loader::validate('Admin');
        if(!$validate->check($data)){
            return ['error'=>1,'info'=>$validate->getError()];
        }
        $data['password']=md5($data['pass']);
        // 启动事务
        // var_dump($insertData);
        Db::startTrans();
        try{
            //插入管理员表
            $res = Db::table('admin')->insert($data);
            $insertMid['aid'] = Db::table('admin')->getLastInsID();
            $insertMid['rid'] = $data['rid'];
            $res = Db::table('auth_role')->insert($insertMid);
            // 提交事务
            Db::commit();
            return ['error'=>0,'info'=>'success'];    
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ['error'=>1,'info'=>'增加管理员失败'];
        }


    }

}


?>